<template>
  <view class="pindou-page">
    <!-- 头部标题 -->
    <view class="header">
      <text class="title">拼豆工坊</text>
      <text class="subtitle">将图片转换为像素艺术风格</text>
    </view>

    <!-- 上传区域 -->
    <view class="upload-section">
      <view class="upload-area" @click="chooseImage">
        <image v-if="!originalImage" class="upload-icon" src="/static/icons/upload.png" mode="aspectFit"></image>
        <view v-else class="image-container">
          <view class="crop-box" :style="{ width: cropBoxSize + 'px', height: cropBoxSize + 'px' }">
            <image 
              class="preview-image" 
              :src="originalImage" 
              mode="aspectFit" 
              :style="{
                transform: `scale(${imageScale}) translate(${imagePosition.x / imageScale}px, ${imagePosition.y / imageScale}px)`
              }"
              @load="onImageLoad" 
              @touchstart="onTouchStart" 
              @touchmove="onTouchMove" 
              @touchend="onTouchEnd"
            ></image>
            <view class="crop-border"></view>
          </view>
          <view class="zoom-controls">
            <button class="zoom-btn" @click.stop="zoomOut">➖</button>
            <button class="zoom-btn" @click.stop="zoomIn">➕</button>
            <button class="zoom-btn" @click.stop="resetZoom">🔄</button>
          </view>
        </view>
        <text class="upload-text">{{ originalImage ? '点击更换图片' : '点击上传图片' }}</text>
      </view>
    </view>

    <!-- 设置区域 -->
    <view class="settings-section" v-if="originalImage">
      <!-- 尺寸选择 -->
      <view class="setting-group">
        <text class="setting-label">像素尺寸</text>
        <view class="size-options">
          <view 
            v-for="size in presetSizes" 
            :key="size.value"
            :class="['size-option', selectedSize === size.value ? 'selected' : '']"
            @click="selectSize(size.value)"
          >
            <text class="size-text">{{ size.label }}</text>
          </view>
        </view>
      </view>

      <!-- 色板设置 -->
      <view class="setting-group">
        <text class="setting-label">颜色数量</text>
        <view class="color-options">
          <view 
            v-for="count in colorPresets" 
            :key="count"
            :class="['color-option', colorCount === count ? 'selected' : '']"
            @click="selectColorCount(count)"
          >
            <text class="color-count-option-text">{{ count }}色</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 生成区域 -->
    <view class="generate-section" v-if="originalImage">
      <!-- 进度条 -->
      <view v-if="generatingProgress > 0" class="progress-container">
        <view class="progress-bar">
          <view 
            class="progress-fill" 
            :style="{ width: generatingProgress + '%' }"
          ></view>
        </view>
        <text class="progress-text">{{ generatingProgress }}% 正在生成像素画...</text>
      </view>
      
      <button class="generate-btn" @click="generatePixelArt" :disabled="isGenerating">
        <text v-if="!isGenerating">生成像素画</text>
        <text v-else>生成中...</text>
      </button>
    </view>

    <!-- 预览区域 -->
    <view class="preview-section" v-if="previewPixelImage && !pixelImage">
      <view class="preview-header">
        <text class="preview-title">实时预览</text>
        <text class="preview-size">预览效果 ({{ finalSize.width }} × {{ finalSize.height }})</text>
      </view>
      <view class="preview-container">
        <image class="preview-image" :src="previewPixelImage" mode="aspectFit"></image>
      </view>
    </view>

    <!-- 结果区域 -->
    <view class="result-section" v-if="pixelImage">
      <view class="result-header">
        <text class="result-title">像素艺术</text>
        <view class="result-info">
          <text class="result-size">{{ finalSize.width }} × {{ finalSize.height }}</text>
          <text class="result-colors">{{ usedColors.length }} 种颜色</text>
        </view>
      </view>

      <!-- 像素图片展示 -->
      <view class="pixel-container">
        <image class="pixel-image" :src="pixelImage" mode="aspectFit"></image>
      </view>

      <!-- 色号展示 -->
      <view class="color-palette">
        <text class="palette-title">色号表</text>
        <view class="palette-grid">
          <view 
            v-for="(color, index) in usedColors" 
            :key="index"
            class="color-item"
          >
            <view class="color-box" :style="{ backgroundColor: color.hex }"></view>
            <text class="color-hex">{{ color.hex }}</text>
            <text class="color-rgb">{{ color.rgb }}</text>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button class="save-btn" @click="saveToAlbum">
          <text>保存到相册</text>
        </button>
        <button class="share-btn" @click="shareImage">
          <text>分享</text>
        </button>
        <button class="ai-btn" @click="showAIDialog">
          <text>AI 生成</text>
        </button>
      </view>
    </view>

    <!-- AI 生成提示 -->
    <view class="ai-note" v-if="!originalImage">
      <text class="note-icon">🤖</text>
      <text class="note-text">注：后续将接入DeepSeek AI生成像素图片</text>
    </view>

    <!-- AI 对话框 -->
    <u-popup v-model:show="showAI" mode="center" border-radius="20">
      <view class="ai-dialog">
        <view class="dialog-header">
          <text class="dialog-title">AI 像素生成</text>
          <text class="dialog-close" @click="showAI = false">×</text>
        </view>
        <view class="dialog-content">
          <text class="dialog-text">使用AI生成像素图片功能即将上线！</text>
          <text class="dialog-subtext">描述您想要的像素画，AI将为您生成</text>
          <textarea 
            class="ai-input"
            v-model="aiPrompt"
            placeholder="例如：一只可爱的小猫，像素风格..."
            maxlength="200"
          />
        </view>
        <view class="dialog-actions">
          <button class="cancel-btn" @click="showAI = false">取消</button>
          <button class="confirm-btn" @click="generateWithAI" :disabled="!aiPrompt.trim()">生成</button>
        </view>
      </view>
    </u-popup>

    <!-- 隐藏的canvas用于图片处理 -->
    <canvas 
      canvas-id="pixelCanvas" 
      :style="{ 
        width: finalSize.width + 'px', 
        height: finalSize.height + 'px',
        position: 'absolute',
        top: '-3000px',
        left: '-3000px',
        visibility: 'hidden'
      }"
    ></canvas>

    <!-- 临时canvas用于裁剪 -->
    <canvas 
      canvas-id="tempCropCanvas" 
      :style="{ 
        width: cropBoxSize + 'px', 
        height: cropBoxSize + 'px',
        position: 'absolute',
        top: '-3000px',
        left: '-3000px',
        visibility: 'hidden'
      }"
    ></canvas>
  </view>
</template>

<script>
export default {
  data() {
    return {
      originalImage: null,
      pixelImage: null,
      previewPixelImage: null,
      selectedSize: '32x32',
      cropBoxSize: 300,
      imageScale: 1,
      imagePosition: { x: 0, y: 0 },
      isDragging: false,
      lastTouch: { x: 0, y: 0 },
      imageLoaded: false,
      canvasReady: false,
      isGenerating: false,
      generatingProgress: 0,
      colorCount: 32,
      usedColors: [],
      finalSize: { width: 32, height: 32 },
      presetSizes: [
        { label: '32×32', value: '32x32' },
        { label: '40×40', value: '40x40' }
      ],
      colorPresets: [32, 64, 128],
      showAI: false,
      aiPrompt: ''
    }
  },

  methods: {
    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: ({ tempFilePaths }) => {
          this.originalImage = tempFilePaths[0]
          this.pixelImage = null // 清空之前的生成结果
        },
        fail: () => {
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          })
        }
      })
    },

    // 图片加载完成
    onImageLoad() {
      this.imageLoaded = true
      this.resetZoom()
    },

    // 放大图片
    zoomIn() {
      this.imageScale = Math.min(this.imageScale * 1.2, 3)
    },

    // 缩小图片
    zoomOut() {
      this.imageScale = Math.max(this.imageScale * 0.8, 0.5)
    },

    // 重置缩放
    resetZoom() {
      this.imageScale = 1
      this.imagePosition = { x: 0, y: 0 }
    },

    // 触摸开始
    onTouchStart(e) {
      if (!this.imageLoaded) return
      this.isDragging = true
      const touch = e.touches[0]
      this.lastTouch = { x: touch.clientX, y: touch.clientY }
    },

    // 触摸移动
    onTouchMove(e) {
      if (!this.isDragging || !this.imageLoaded) return
      e.preventDefault()
      
      const touch = e.touches[0]
      const deltaX = touch.clientX - this.lastTouch.x
      const deltaY = touch.clientY - this.lastTouch.y
      
      this.imagePosition.x += deltaX
      this.imagePosition.y += deltaY
      
      this.lastTouch = { x: touch.clientX, y: touch.clientY }
    },

    // 触摸结束
    onTouchEnd() {
      this.isDragging = false
    },

    // 获取裁剪区域的图片数据
    getCroppedImageData() {
      return new Promise((resolve, reject) => {
        // 创建临时canvas用于裁剪
        const tempCanvasId = 'tempCropCanvas'
        const ctx = uni.createCanvasContext(tempCanvasId, this)
        
        // 设置裁剪区域尺寸
        const cropSize = this.cropBoxSize
        
        // 清空画布
        ctx.clearRect(0, 0, cropSize, cropSize)
        
        // 应用变换并绘制图片
        ctx.save()
        
        // 计算缩放后的图片尺寸
        uni.getImageInfo({
          src: this.originalImage,
          success: (imageInfo) => {
            const scaledWidth = imageInfo.width * this.imageScale
            const scaledHeight = imageInfo.height * this.imageScale
            
            // 居中绘制缩放并移动后的图片
            const centerX = cropSize / 2 + this.imagePosition.x
            const centerY = cropSize / 2 + this.imagePosition.y
            
            ctx.drawImage(
              this.originalImage,
              centerX - scaledWidth / 2,
              centerY - scaledHeight / 2,
              scaledWidth,
              scaledHeight
            )
            
            ctx.restore()
            ctx.draw(false, () => {
              // 导出裁剪后的图片
              uni.canvasToTempFilePath({
                canvasId: tempCanvasId,
                width: cropSize,
                height: cropSize,
          success: ({ tempFilePath }) => {
            resolve(tempFilePath)
          },
                fail: reject
              })
            })
          },
          fail: reject
        })
      })
    },

    // 选择尺寸
    selectSize(size) {
      this.selectedSize = size
      const [width, height] = size.split('x').map(Number)
      this.finalSize = { width, height }
      // 如果有图片，生成预览
      if (this.originalImage) {
        this.generatePreview()
      }
    },

    // 选择颜色数量
    selectColorCount(count) {
      this.colorCount = count
      // 如果有图片，生成预览
      if (this.originalImage) {
        this.generatePreview()
      }
    },

    // 生成预览（低分辨率快速预览）
    async generatePreview() {
      if (!this.originalImage) return
      
      try {
        // 先获取裁剪区域的图片进行预览
        const croppedImage = await this.getCroppedImageData()
        
        // 使用较小尺寸快速预览
        const previewSize = Math.max(this.finalSize.width, this.finalSize.height)
        const scaleFactor = previewSize > 40 ? 0.6 : 1
        
        const previewData = await this.processImageToPixel(
          croppedImage, 
          { 
            width: Math.floor(this.finalSize.width * scaleFactor), 
            height: Math.floor(this.finalSize.height * scaleFactor) 
          },
          this.colorCount
        )
        this.previewPixelImage = previewData.imagePath
      } catch (error) {
        console.error('预览生成失败:', error)
      }
    },

    // 生成像素画
    async generatePixelArt() {
      this.isGenerating = true
      this.generatingProgress = 0
      
      try {
        // 先获取裁剪区域的图片
        this.generatingProgress = 10
        const croppedImage = await this.getCroppedImageData()
        
        // 使用canvas进行像素化处理
        this.generatingProgress = 30
        const pixelData = await this.processImageToPixel(croppedImage, this.finalSize, this.colorCount)
        
        this.generatingProgress = 80
        this.pixelImage = pixelData.imagePath
        this.usedColors = pixelData.colors
        
        this.generatingProgress = 100
        
        setTimeout(() => {
          uni.showToast({
            title: '生成成功！',
            icon: 'success'
          })
          this.generatingProgress = 0
        }, 500)
      } catch (error) {
        console.error('生成失败:', error)
        uni.showModal({
          title: '生成失败',
          content: '图片处理失败，请检查图片格式是否正确，或尝试更换图片。',
          showCancel: false,
          confirmText: '我知道了'
        })
      } finally {
        this.isGenerating = false
        setTimeout(() => {
          this.generatingProgress = 0
        }, 1000)
      }
    },

    // 处理图片为像素风格
    async processImageToPixel(imagePath, size = this.finalSize, colorCount = this.colorCount) {
      return new Promise((resolve, reject) => {
        const canvasId = 'pixelCanvas'
        const ctx = uni.createCanvasContext(canvasId, this)
        
        // 清空画布
        ctx.clearRect(0, 0, size.width, size.height)
            
            // 先绘制完整图片到canvas
            ctx.drawImage(imagePath, 0, 0, size.width, size.height)
            
            ctx.draw(false, () => {
              // 获取图片数据进行像素化处理
              uni.canvasGetImageData({
                canvasId,
                x: 0,
                y: 0,
                width: size.width,
                height: size.height,
                success: (res) => {
                  try {
                    const pixelatedData = this.pixelateImageData(res.data, size.width, size.height, colorCount)
                    const colors = this.extractColors(pixelatedData, colorCount)
                    
                    // 将处理后的数据绘制回canvas
                    ctx.putImageData({
                      data: pixelatedData,
                      x: 0,
                      y: 0,
                      width: size.width,
                      height: size.height
                    })
                    
                    ctx.draw(false, () => {
                      // 导出为图片
                      uni.canvasToTempFilePath({
                        canvasId,
                        success: ({ tempFilePath }) => {
                          resolve({
                            imagePath: tempFilePath,
                            colors
                          })
                        },
                        fail: (err) => {
                          console.error('导出图片失败:', err)
                          reject(err)
                        }
                      })
                    })
                  } catch (error) {
                    console.error('像素化处理失败:', error)
                    reject(error)
                  }
                },
                fail: (err) => {
                  console.error('获取图片数据失败:', err)
                  reject(err)
                }
              })
            })
      })
    },

    // 像素化处理
    pixelateImageData(imageData, width, height, colorCount) {
      const data = new Uint8ClampedArray(imageData)
      
      // 块大小，根据像素尺寸计算
      const blockSize = Math.max(Math.floor(width / 16), 1)
      
      for (let y = 0; y < height; y += blockSize) {
        for (let x = 0; x < width; x += blockSize) {
          // 计算块内平均颜色
          let totalR = 0
          let totalG = 0
          let totalB = 0
          let count = 0
          
          for (let dy = 0; dy < blockSize && y + dy < height; dy += 1) {
            for (let dx = 0; dx < blockSize && x + dx < width; dx += 1) {
              const i = ((y + dy) * width + (x + dx)) * 4
              totalR += data[i]
              totalG += data[i + 1]
              totalB += data[i + 2]
              count += 1
            }
          }
          
          if (count > 0) {
            const avgR = Math.floor(totalR / count)
            const avgG = Math.floor(totalG / count)
            const avgB = Math.floor(totalB / count)
            
            // 量化颜色
            const quantizedColor = this.quantizeColor(avgR, avgG, avgB, colorCount)
            
            // 填充块
            for (let dy = 0; dy < blockSize && y + dy < height; dy += 1) {
              for (let dx = 0; dx < blockSize && x + dx < width; dx += 1) {
                const i = ((y + dy) * width + (x + dx)) * 4
                data[i] = quantizedColor.r
                data[i + 1] = quantizedColor.g
                data[i + 2] = quantizedColor.b
                data[i + 3] = 255
              }
            }
          }
        }
      }
      
      return data
    },

    // 颜色量化
    quantizeColor(r, g, b, colorCount) {
      // 根据颜色数量调整量化级别
      let level = 8 // 256色
      if (colorCount <= 32) level = 16
      else if (colorCount <= 64) level = 8
      else if (colorCount <= 128) level = 4
      
      return {
        r: Math.floor(r / level) * level,
        g: Math.floor(g / level) * level,
        b: Math.floor(b / level) * level
      }
    },

    // 提取主要颜色
    extractColors(imageData, maxColors) {
      const colorMap = new Map()
      const data = imageData.data
      
      for (let i = 0; i < data.length; i += 4) {
        const r = data[i]
        const g = data[i + 1]
        const b = data[i + 2]
        const a = data[i + 3]
        
        if (a > 0) { // 忽略透明像素
          const key = `${r},${g},${b}`
          colorMap.set(key, (colorMap.get(key) || 0) + 1)
        }
      }
      
      // 按出现频率排序，取前N个颜色
      const sortedColors = Array.from(colorMap.entries())
        .sort((a, b) => b[1] - a[1])
        .slice(0, maxColors)
        .map(([color]) => {
          const [r, g, b] = color.split(',').map(Number)
          return {
            rgb: `rgb(${r}, ${g}, ${b})`,
            hex: this.rgbToHex(r, g, b)
          }
        })
      
      return sortedColors
    },

    // RGB转HEX
    rgbToHex(r, g, b) {
      return `#${[r, g, b]
        .map(x => {
          const hex = x.toString(16)
          return hex.length === 1 ? '0' + hex : hex
        })
        .join('')}`
    },

    // 保存到相册
    saveToAlbum() {
      if (!this.pixelImage) return
      
      // 先检查权限
      uni.getSetting({
        success: (res) => {
          if (res.authSetting['scope.writePhotosAlbum']) {
            // 已授权，直接保存
            this.doSaveImage()
          } else if (res.authSetting['scope.writePhotosAlbum'] === false) {
            // 用户拒绝过，引导去设置
            uni.showModal({
              title: '需要相册权限',
              content: '保存图片需要访问相册权限，请在设置中开启权限',
              confirmText: '去设置',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  uni.openSetting()
                }
              }
            })
          } else {
            // 首次使用，请求授权
            uni.authorize({
              scope: 'scope.writePhotosAlbum',
              success: () => {
                this.doSaveImage()
              },
              fail: () => {
                uni.showToast({
                  title: '授权失败，无法保存',
                  icon: 'none'
                })
              }
            })
          }
        }
      })
    },

    // 执行保存操作
    doSaveImage() {
      uni.showLoading({
        title: '保存中...'
      })
      
      uni.saveImageToPhotosAlbum({
        filePath: this.pixelImage,
        success: () => {
          uni.hideLoading()
          uni.showModal({
            title: '保存成功',
            content: '像素画已保存到相册，可以在相册中查看！',
            showCancel: false,
            confirmText: '知道了'
          })
        },
        fail: (err) => {
          uni.hideLoading()
          console.error('保存失败:', err)
          uni.showModal({
            title: '保存失败',
            content: '保存图片失败，请检查相册权限或稍后重试',
            showCancel: false,
            confirmText: '知道了'
          })
        }
      })
    },

    // 分享图片
    shareImage() {
      if (!this.pixelImage) return
      
      uni.showActionSheet({
        itemList: ['分享给好友'],
        success: (res) => {
          if (res.tapIndex === 0) {
            // 实际项目中可以接入分享SDK
            uni.showToast({
              title: '分享功能开发中',
              icon: 'none'
            })
          }
        }
      })
    },

    // 显示AI对话框
    showAIDialog() {
      this.showAI = true
    },

    // AI生成（预留接口）
    generateWithAI() {
      uni.showToast({
        title: 'AI功能即将上线',
        icon: 'none'
      })
      this.showAI = false
    }
  },

  // 分享配置
  onShareAppMessage() {
    return {
      title: '拼豆工坊 - 像素艺术生成器',
      path: '/pages-sub/pindou/index',
      imageUrl: '/static/share-img.png'
    }
  },

  onShareTimeline() {
    return {
      title: '拼豆工坊 - 像素艺术生成器',
      imageUrl: '/static/share-img.png'
    }
  }
}
</script>

<style lang="scss">
// 活泼创意主题色
$primary: #667eea;
$secondary: #764ba2;
$accent: #f093fb;
$success: #4facfe;
$warning: #43e97b;
$bg: #f7fafc;
$card-bg: #ffffff;
$border-radius: 24rpx;

.pindou-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 32rpx;
}

.header {
  text-align: center;
  margin-bottom: 40rpx;

  .title {
    font-size: 48rpx;
    font-weight: bold;
    color: white;
    display: block;
    margin-bottom: 16rpx;
    text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
  }

  .subtitle {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
    display: block;
  }
}

.upload-section {
  margin-bottom: 40rpx;
}

.upload-area {
  background: rgba(255, 255, 255, 0.95);
  border-radius: $border-radius;
  padding: 60rpx 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);

  .upload-icon {
    width: 120rpx;
    height: 120rpx;
    margin-bottom: 24rpx;
    border-radius: 16rpx;
  }

  .image-container {
    position: relative;
    margin-bottom: 24rpx;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .crop-box {
    position: relative;
    width: 300px;
    height: 300px;
    overflow: hidden;
    border-radius: 16rpx;
    background: #f5f5f5;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);

    .preview-image {
      width: 100%;
      height: 100%;
      object-fit: contain;
      transition: transform 0.3s ease;
    }

    .crop-border {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      border: 4rpx solid rgba(102, 126, 234, 0.6);
      border-radius: 16rpx;
      pointer-events: none;
    }
  }

  .zoom-controls {
    display: flex;
    gap: 12rpx;
    margin-top: 20rpx;

    .zoom-btn {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.9);
      border: 2rpx solid #e0e0e0;
      font-size: 32rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.95);
        background: #f0f0f0;
      }
    }
  }

  .upload-text {
    font-size: 28rpx;
    color: #666;
  }
}

.settings-section {
  margin-bottom: 32rpx;
}

.setting-group {
  background: rgba(255, 255, 255, 0.95);
  border-radius: $border-radius;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);

  .setting-label {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    display: block;
    margin-bottom: 24rpx;
  }
}

.size-options {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.size-option {
  padding: 16rpx 24rpx;
  border-radius: 20rpx;
  border: 2rpx solid #e0e0e0;
  background: white;
  transition: all 0.3s ease;

  &.selected {
    border-color: $primary;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
  }

  .size-text {
    font-size: 28rpx;
    color: #333;
  }

  .custom-input {
    width: 100rpx;
    height: 40rpx;
    border: none;
    background: transparent;
    text-align: center;
    font-size: 28rpx;
  }

  &.custom-size {
    flex: 1;
    min-width: 200rpx;
  }

  .custom-inputs {
    display: flex;
    align-items: center;
    gap: 8rpx;

    .custom-input-small {
      width: 80rpx;
      height: 40rpx;
      border: 1rpx solid #ddd;
      border-radius: 8rpx;
      text-align: center;
      font-size: 26rpx;
      background: white;
    }

    .size-separator {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.color-options {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-bottom: 20rpx;
}

.color-option {
  padding: 12rpx 20rpx;
  border-radius: 16rpx;
  border: 2rpx solid #e0e0e0;
  background: white;
  transition: all 0.3s ease;

  &.selected {
    border-color: $primary;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
  }

  .color-count-option-text {
    font-size: 26rpx;
    color: #333;
  }
}

.color-slider-container {
  margin-top: 16rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.progress-container {
  margin-bottom: 24rpx;
}

.progress-bar {
  width: 100%;
  height: 8rpx;
  background: #f0f0f0;
  border-radius: 4rpx;
  overflow: hidden;
  margin-bottom: 12rpx;

  .progress-fill {
    height: 100%;
    background: linear-gradient(135deg, $primary, $secondary);
    border-radius: 4rpx;
    transition: width 0.3s ease;
  }
}

.progress-text {
  font-size: 24rpx;
  color: #666;
  text-align: center;
  display: block;
}

.generate-section {
  margin-bottom: 40rpx;
}

.preview-section {
  background: rgba(255, 255, 255, 0.9);
  border-radius: $border-radius;
  padding: 24rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;

  .preview-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #666;
  }

  .preview-size {
    font-size: 22rpx;
    color: #999;
  }
}

.preview-container {
  display: flex;
  justify-content: center;

  .preview-image {
    border-radius: 12rpx;
    max-width: 200rpx;
    max-height: 200rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    opacity: 0.8;
  }
}

.generate-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, $primary, $secondary);
  color: white;
  border: none;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: bold;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.3);

  &[disabled] {
    background: #ccc;
    box-shadow: none;
  }
}

.result-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: $border-radius;
  padding: 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;

  .result-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }

  .result-info {
    display: flex;
    gap: 16rpx;

    .result-size,
    .result-colors {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.pixel-container {
  margin-bottom: 32rpx;
  display: flex;
  justify-content: center;

  .pixel-image {
    border-radius: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
    max-width: 300rpx;
    max-height: 300rpx;
  }
}

.color-palette {
  margin-bottom: 32rpx;
}

.palette-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 20rpx;
}

.palette-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16rpx;
}

.color-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16rpx;
  border-radius: 16rpx;
  background: #f8f9fa;

  .color-box {
    width: 60rpx;
    height: 60rpx;
    border-radius: 12rpx;
    margin-bottom: 12rpx;
    border: 1rpx solid #e0e0e0;
  }

  .color-hex,
  .color-rgb {
    font-size: 20rpx;
    color: #666;
    text-align: center;
  }
}

.action-buttons {
  display: flex;
  gap: 16rpx;
}

.save-btn,
.share-btn,
.ai-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
}

.save-btn {
  background: $success;
  color: white;
}

.share-btn {
  background: $warning;
  color: white;
}

.ai-btn {
  background: $accent;
  color: white;
}

.ai-note {
  background: rgba(255, 255, 255, 0.1);
  border-radius: $border-radius;
  padding: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
  margin-top: 40rpx;

  .note-icon {
    font-size: 36rpx;
  }

  .note-text {
    font-size: 26rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.ai-dialog {
  background: white;
  border-radius: $border-radius;
  padding: 40rpx;
  width: 600rpx;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;

  .dialog-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }

  .dialog-close {
    font-size: 48rpx;
    color: #999;
    padding: 8rpx;
  }
}

.dialog-content {
  margin-bottom: 32rpx;

  .dialog-text {
    font-size: 32rpx;
    color: #333;
    display: block;
    margin-bottom: 16rpx;
  }

  .dialog-subtext {
    font-size: 26rpx;
    color: #666;
    display: block;
    margin-bottom: 24rpx;
  }

  .ai-input {
    width: 100%;
    height: 120rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 16rpx;
    padding: 20rpx;
    font-size: 28rpx;
    background: #f8f9fa;
  }
}

.dialog-actions {
  display: flex;
  gap: 16rpx;
}

.cancel-btn,
.confirm-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
}

.cancel-btn {
  background: #f0f0f0;
  color: #666;
}

.confirm-btn {
  background: $primary;
  color: white;

  &[disabled] {
    background: #ccc;
  }
}
</style>